import { http, HttpResponse } from 'msw'

/**
 * 创建用户列表函数
 * @description 返回包含用户信息的数组
 * @returns {Array} 用户信息数组
 */
function createUserList() {
  return [
    {
      userId: 1,
      avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      username: 'admin',
      password: '111111',
      desc: '平台管理员',
      roles: ['平台管理员'],
      buttons: ['cuser.detail'],
      routes: ['home'],
      token: 'Admin Token',
    },
    {
      userId: 2,
      avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      username: 'system',
      password: '111111',
      desc: '系统管理员',
      roles: ['系统管理员'],
      buttons: ['cuser.detail', 'cuser.user'],
      routes: ['home'],
      token: 'System Token',
    },
  ]
}

/**
 * 用户登录 Mock 接口
 * @description 模拟用户登录功能，验证用户名和密码
 */
export const userLoginHandler = http.post('/api/user/login', async ({ request }) => {
  const { username, password } = await request.json() as { username: string; password: string }

  // 调用获取用户信息函数，用于判断是否有此用户
  const checkUser = createUserList().find(
    (item) => item.username === username && item.password === password,
  )

  // 没有用户返回失败信息
  if (!checkUser) {
    return HttpResponse.json({
      code: 201,
      message: '账号或者密码不正确'
    })
  }

  // 如果有返回成功信息
  const { token } = checkUser
  return HttpResponse.json({
    code: 200,
    message:'登录成功',
    data: { token }
  })
})

/**
 * 获取用户信息 Mock 接口
 * @description 根据 token 获取当前用户信息
 */
export const getUserInfoHandler = http.get('/api/user/info', ({ request }) => {
  // 获取请求头携带token
  const token = request.headers.get('token')

  // 查看用户信息是否包含有此token用户
  const checkUser = createUserList().find((item) => item.token === token)

  // 没有返回失败的信息
  if (!checkUser) {
    return HttpResponse.json({
      code: 201,
      message: '获取用户信息失败'
    })
  }

  // 如果有返回成功信息
  return HttpResponse.json({
    code: 200,
    data: checkUser
  })
})

/**
 * 获取用户列表 Mock 接口
 * @description 分页获取用户列表数据
 */
export const getUserListHandler = http.get('/api/user/list', ({ request }) => {
  const url = new URL(request.url)
  const page = parseInt(url.searchParams.get('page') || '1')
  const pageSize = parseInt(url.searchParams.get('pageSize') || '10')

  // 模拟用户数据
  const users = Array.from({ length: 50 }, (_, index) => ({
    id: index + 1,
    username: `user${index + 1}`,
    nickname: `用户${index + 1}`,
    email: `user${index + 1}@example.com`,
    avatar: `https://via.placeholder.com/100x100?text=User${index + 1}`,
    role: index % 3 === 0 ? 'admin' : 'user',
    status: index % 5 === 0 ? 'disabled' : 'active',
    createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString()
  }))

  // 分页处理
  const startIndex = (page - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedUsers = users.slice(startIndex, endIndex)

  return HttpResponse.json({
    code: 200,
    message: '获取成功',
    data: {
      list: paginatedUsers,
      total: users.length,
      page,
      pageSize,
      totalPages: Math.ceil(users.length / pageSize)
    }
  })
})

// 导出所有用户相关的处理器
export const userHandlers = [
  userLoginHandler,
  getUserInfoHandler,
  getUserListHandler
]
